const bcrypt = require("bcryptjs");

const { getUserInfo } = require("../server/user.server");

const {
  createServer,
  getRolesByUserId,
} = require("../server/role-user.server");
const { getRoleServer } = require("../server/role.server");

const {
  userFormateError,
  userAlreadyExited,
  userRegisterError,
  userDoesNotExist,
  userLoginError,
  invalidPassword,
} = require("../constants/err.type");

// 用户名密码 验证
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    console.error("用户名或密码为空", ctx.request.body);
    (ctx.status = 400), (ctx.body = userFormateError);
    // ctx.body = {
    //   code:'10001',
    //   messsage:'用户名或密码为空',
    //   result:''
    // }
    returnauth;
  }
  await next();
};

// 用户是否存在 验证
const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  // if( await getUserInfo({ user_name })){
  //   ctx.status = 409,
  //   ctx.app.emit('error',userAlreadyExited,ctx)

  //   ctx.body = {
  //     code:"10002",
  //     message:"用户已存在",
  //     result:'',
  //   }
  //   return
  // }
  try {
    const res = await getUserInfo({
      user_name,
    });
    if (res) {
      console.error("用户名已存在", {
        user_name,
      });
      ctx.body = userAlreadyExited;
      return;
    }
  } catch (error) {
    console.error("获取用户信息错误", error);
    ctx.body = userRegisterError;
    return;
  }
  await next();
};

// 密码加密
const bcryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;
  await next();
};

// 登录验证
const verifyLogin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;

  try {
    const res = await getUserInfo({
      user_name,
    });
    if (!res) {
      console.error("用户名不存在", {
        user_name,
      });
      ctx.body = userDoesNotExist;
      return;
    }
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.body = invalidPassword;
      return;
    }
  } catch (error) {
    console.error("用户登录失败", error);
    ctx.body = userLoginError;
    return;
  }

  await next();
};

// 绑定用户角色
const bindRoleUser = async (ctx, next) => {
  // roleId：100 默认普通用户
  if (
    ctx.state.user.roleId
      ? ctx.state.user.roleId
      : (ctx.state.user.roleId = 100)
  ) {
    try {
      const res = await createServer([
        {
          userId: ctx.state.user.id,
          roleId: ctx.state.user.roleId,
        },
      ]);
    } catch (error) {
      console.error("用户注册失败", error);
    }
  }
  await next();
};
// 获取用户角色
const getRoleUser = async (ctx, next) => {
  const res = await getRolesByUserId(ctx.state.user.id);
  const result = await getRoleServer(res);
  const roleName = [];
  const roleIds = [];
  result.map((item) => {
    roleName.push(item.name);
    roleIds.push(item.id);
  });
  (ctx.state.user = {
    roleName,
    roleIds,
    ...ctx.state.user,
  }),
    await next();
};

const registerReturn = async (ctx, next) => {
  const { roleId, ...result } = ctx.state.user;
  try {
    ctx.body = {
      code: 0,
      message: "用户注册成功",
      result: result,
    };
  } catch (error) {
    console.error(error);
    ctx.body = userRegisterError;
  }
};

module.exports = {
  userValidator,
  verifyUser,
  bcryptPassword,
  verifyLogin,
  bindRoleUser,
  getRoleUser,
  registerReturn,
};
